package com.broada.apm.template.impl;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.broada.apm.template.ResourceTemplate;
import com.broada.apm.utils.ApmFileUtils;
import com.broada.apm.utils.JsonUtil;

/**
 * json资源配置模板默认实现
 * @author jianfei.xu
 * @date   2016年3月16日
 *
 * @param <T>
 */
public class DefaultJsonResourceTemplate<T> implements ResourceTemplate<T> {
	
	@Override
	public List<T> getAll(Class<T> entityClass) {
		if(null == jsonPath || "".equals(jsonPath)) return null;
		try {
			return JsonUtil.json2list(readJsonFile(jsonPath), entityClass);
		} catch (Exception e) {
			LOG.error("解析" + jsonPath + "文件内容出错", e);
		}
		
		return null;
	}
	
	@Override
	public List<T> getByParams(T queryParam, Class<T> entityClass) {
		return null;
	}

	@Override
	public int deleteByParams(T delParam, Class<T> entityClass) {
		return 0;
	}

	@Override
	public int updateByParams(T updateParam, Class<T> entityClass) {
		return 0;
	}

	@Override
	public int add(T entity, Class<T> entityClass) {
		return 0;
	}

	public DefaultJsonResourceTemplate(String jsonPath) {
		this.jsonPath = tryLocateXmlAbsolutePath(jsonPath);
	}
	
	/**
	 * 读取json文件中内容
	 * @param jsonPath	:json文件地址
	 * @return			:返回文件内容
	 */
	private String readJsonFile(String jsonPath) {
		BufferedReader BufReader = null;
		StringBuffer retBuf = new StringBuffer();
		FileInputStream fileInputStream = null;
		try {
			fileInputStream = new FileInputStream(jsonPath);
		} catch (FileNotFoundException e) {
			LOG.error(jsonPath + "文件不存在", e);
			return null;
		}
		
		try {
			InputStreamReader inputStreamReader = new InputStreamReader(fileInputStream);
			BufReader = new BufferedReader(inputStreamReader);
			String tmpStr = null;
			while(null != (tmpStr = BufReader.readLine())) {
				retBuf.append(tmpStr);
			}
		} catch(IOException e) {
			LOG.error("读取" + jsonPath + "文件内容出错", e);
		} finally {
			if(null != BufReader){
				try {
					BufReader.close();
				} catch (IOException e) {
					LOG.error("关闭流出错", e);
				}
			}
		}
		
		return retBuf.toString();
	}
	
	/**
	 * 尝试定位json绝对位置
	 * @param jsonPath	:给定的参数位置
	 * @return			:返回绝对定位
	 */
	private String tryLocateXmlAbsolutePath(String jsonPath) {
		if(null == jsonPath || "".equals(jsonPath)) return jsonPath;
		Class<?> cls = this.getClass();
		URL xmlURL = cls.getResource(jsonPath);
		if(null != xmlURL) {
			jsonPath = xmlURL.getPath();
			return jsonPath;
		}
		
		File tmpFile = ApmFileUtils.getFile(jsonPath);
		if(tmpFile.exists()) {
			jsonPath = tmpFile.getAbsolutePath();
			return jsonPath;
		}
		
		return jsonPath;
	}

	private String jsonPath; //json文件路径
	
	private static Logger LOG = LoggerFactory.getLogger(DefaultJsonResourceTemplate.class);
	
}
